package com.epoch.base.shiro.ext;

import com.epoch.base.util.MD5Utils;
import com.epoch.platform.sys.user.dao.SysUser;
import com.jfinal.kit.StrKit;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.cache.Cache;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.session.SessionException;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.subject.SimplePrincipalCollection;


public class ShiroDbRealm extends AuthorizingRealm {

    public ShiroDbRealm() {
        setAuthenticationTokenClass(CaptchaUsernamePasswordToken.class);
    }

    /**
     * 认证回调函数,登录时调用.
     */
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) {
        String username = (String) token.getPrincipal();
        if (StrKit.isBlank(username)) {
            throw new AuthenticationException("用户名不可以为空");
        }
        UsernamePasswordToken upToken = (UsernamePasswordToken) token;
        String password = new String(upToken.getPassword());
        password = MD5Utils.getMd5(password);
        upToken.setPassword(password.toCharArray());
        String sql = "select * from SYS_USER u where u.account ='" + username + "' or u.email = '" + username + "' or u.employee_number='" + username + "'";
        SysUser sysUser = SysUser.dao.findFirst(sql);
        if (sysUser == null) {
            throw new SessionException("用户名或者密码错误");
        } 
        //加载用户当前角色
//        UserRole aUserRoledaoFirst = UserRole.dao.findFirst(Db.getSql("systemManage.selectUserRoleByUserId"), sysUser.get(SysUser.ID));
//        if (aUserRoledaoFirst != null) {
//            sysUser.put("user_role", aUserRoledaoFirst.getStr("userRoleShow"));
//        }
        // 交给AuthenticatingRealm使用CredentialsMatcher进行密码匹配，如果觉得人家的不好可以自定义实现
        return new SimpleAuthenticationInfo(
                sysUser, // 用户名
                sysUser.getStr(SysUser.PASSWORD), // 密码
                getName() // realm name
        );
    }


    /**
     * 授权查询回调函数, 进行鉴权但缓存中无用户的授权信息时调用.
     */
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
        return new SimpleAuthorizationInfo();
    }


    /**
     * 更新用户授权信息缓存.
     */
    public void clearCachedAuthorizationInfo(String principal) {
        SimplePrincipalCollection principals = new SimplePrincipalCollection(principal, getName());
        clearCachedAuthorizationInfo(principals);
    }

    /**
     * 清除所有用户授权信息缓存.
     */
    public void clearAllCachedAuthorizationInfo() {
        Cache<Object, AuthorizationInfo> cache = getAuthorizationCache();
        if (cache != null) {
            for (Object key : cache.keys()) {
                cache.remove(key);
            }
        }
    }
}
